A regular expression is created with the pattern and optional modifiers:
// Syntax
let pattern = /Technology/i; // 'i' modifier: case-insensitive match
You can create regular expressions using literals or the RegExp
constructor.
// Using literal syntax
const regexLiteral = /abc/;
// Using the RegExp constructor
const regexConstructor = new RegExp('abc');
Modifiers adjust the behavior of a RegExp pattern:
g
: Global matchi
: Case-insensitivem
: Multiline match
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<Script>
const regex = new RegExp(/^a...s$/i);
console.log(regex.test('Alias')); // true
</Script>
</body>
</html>
Brackets define character classes:
[abc]
: Matches any character in abc
[^abc]
: Matches any character not in abc
[0-9]
: Matches any digit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<Script>
const digitRegex = /[0-9]/;
console.log(digitRegex.test('abc123')); // true
</Script>
</body>
</html>
Quantifiers specify the number of occurrences:
*
: Matches zero or more times+
: Matches one or more times{n,m}
: Matches between n
and m
times
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<Script>
const quantifierRegex = /\d{2,4}/;
console.log(quantifierRegex.test('12345')); // true
</Script>
</body>
</html>
Anchors specify position:
^
: Matches start of string$
: Matches end of string
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<Script>
const anchorRegex = /^start/;
console.log(anchorRegex.test('start with regex')); // true
</Script>
</body>
</html>
Escape characters to match symbols:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<Script>
const escapeRegex = /\d+\.\d+/;
console.log(escapeRegex.test('3.14')); // true
</Script>
</body>
</html>
Assertions are used to match specific conditions:
(?=...)
: Positive lookahead(?!...)
: Negative lookahead
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<Script>
const lookaheadRegex = /\w+(?=\s)/;
console.log('Word followed by space'.match(lookaheadRegex)); // ["Word"]
</Script>
</body>
</html>